<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\user;


use app\api\logic\LoginLogic;
use app\common\model\user\{User, UserGroup};
use app\common\logic\BaseLogic;
use think\facade\Db;


/**
 * user逻辑
 * Class UserGroupLogic
 * @package app\adminapi\logic
 */
class UserGroupLogic extends BaseLogic
{


    /**
     * @notes 添加user
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/04/10 10:26
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            $exist = UserGroup::where('email', $params['email'])->count();
            if ($exist) {
                self::setError('邮箱已存在');
                return false;
            }
            $userGroup = UserGroup::create([
                'company_name' => $params['company_name'],
                'remark' => $params['remark'] ?? '',
                'email' => $params['email'],
                'mobile' => $params['mobile'],
                'pid' => $params['pid'] ?? 0,
                'from_business' => $params['from_business'] ?? '',
                'card_limit' => $params['card_limit'] ?? 0,
                'abbreviation' => $params['abbreviation'] ?? '',
                'serverchargerate' => $params['serverchargerate'] ?? 0,
                'serverUchargerate' => $params['serverUchargerate'] ?? 0,
                'tag_ids' => $params['tag_ids'] ?? '',
            ]);

            $params['user_id'] = 0;
            $params['role_id'] = 1;//第一个角色是PA
            $params['group_id'] = $userGroup->id;

            $result = LoginLogic::inviteRegister($params);

            if (!$result) {
                self::setError(LoginLogic::getError());
                return false;
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑user
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/04/10 10:26
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            $row = [];
            // 只添加提交的参数到更新数组
            $updateFields = [
                'company_name',
                'remark',
                'from_business',
                'card_price',
                'abbreviation',
                'serverchargerate',
                'serverUchargerate',
                'card_limit',
                'tag_ids',
                'email',
                'is_disable'
            ];

            foreach ($updateFields as $field) {
                if (isset($params[$field])) {
                    $row[$field] = $params[$field];
                }
            }

            //修改邮箱
            if (isset($params['email'])) {
                // 验证邮箱格式
                if (!filter_var($params['email'], FILTER_VALIDATE_EMAIL)) {
                    self::setError('邮箱格式不正确');
                    return false;
                }
                $exist = UserGroup::where('email', $params['email'])
                    ->where('id', '<>', $params['id']) //不计算自己的原有邮箱
                    ->count();
                if ($exist) {
                    self::setError('邮箱已存在');
                    return false;
                }
                //同步修改该商户的第一个用户邮箱
//                User::where('group_id', $params['id'])
////                    ->where('pid', 0)
////                    ->update(['email' => $params['email']]);
            }

            //修改状态
            if (isset($params['is_disable'])) {
                if (!in_array($params['is_disable'], [0, 1])) {
                    self::setError('状态必须是0和1');
                    return false;
                }
            }


            // 只有在有需要更新的字段时才执行更新
            if (empty($row)) {
                throw new \Exception('没有需要更新的数据');
            }
            UserGroup::where('id', $params['id'])->update($row);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    public static function delete(array $params): bool
    {
        return UserGroup::destroy($params['id']);
    }


    /**
     * @notes 获取user详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2025/04/10 10:26
     */
    public static function detail($params): array
    {
        return UserGroup::findOrEmpty($params['id'])->toArray();
    }
}